package com.weiweb.utils;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class HibernateSessionFactory {


	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static final ThreadLocal<Transaction> threadLocalTran=new ThreadLocal<Transaction>();

    private static SessionFactory sessionFactory;

    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) {
			session = (sessionFactory != null) ? sessionFactory.openSession(): null;
			threadLocal.set(session);
		}
        return session;
    }
    /**
     * start transcation
     * @return
     */
    public static Transaction beginTransaction()  throws HibernateException{
    	Transaction transaction=(Transaction)threadLocalTran.get();
    	if(transaction==null || !transaction.isActive()) {
    		transaction=getSession().beginTransaction();
    		threadLocalTran.set(transaction);
    	}
    	return transaction;
    }
    /**
     * commit transcation
     * @throws HibernateException
     */
    public static void commit() throws HibernateException{
    	Transaction transaction=(Transaction)threadLocalTran.get();
    	transaction.commit();
    }
    /**
     * rollBack transaction
     * @throws HibernateException
     */
    public static void rollBack() throws HibernateException{
    	Transaction transaction=(Transaction)threadLocalTran.get();
    	transaction.rollback();
    }

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);
        if (session != null) {
        		session.close();
        }
    }

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void setSessionFactory(SessionFactory sessionFactory) {
		HibernateSessionFactory.sessionFactory = sessionFactory;
	}

    
	

}